/**
 * 
 */
package com.socialnetwork.user.controller;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.product.profile.model.Profile;
import com.product.profile.service.ProfileService;
import com.socialnetwork.security.pwd.PwdEncryptor;
import com.socialnetwork.user.model.User;
import com.socialnetwork.user.service.UserService;

/**
 * @author asoundar
 *
 */
@Controller
public class Registration {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private JavaMailSender mailSender;
	
	@Autowired
	ProfileService profileService;
	
	@RequestMapping(value = "/SignUp", method = RequestMethod.GET)
	public ModelAndView signUpPage() {
		
		Profile profile = new Profile();
		profile.setGender(true);
		profile.setCreatedFor(1);
		profile.setProfileName("Arun");
		profile.setDateOfBirth(new Date());
		profile.setMaritalStatus(1);
		
		profile.setDateAdded(new Date());
		profile.setDateModified(new Date());
		
		try{
		profileService.addProfile(profile);
		
		//log it via log4j
		if(logger.isDebugEnabled()){
			logger.info(profile);
		}
		
		logger.info(profile);
		
		}catch(Exception exception){
			exception.printStackTrace();
		}
		
		return new ModelAndView("registration-tiles");
	}
	
	@RequestMapping(value = "/SignUp", method = RequestMethod.POST)
	public String addUser(@ModelAttribute("user")User user, BindingResult result) {

		user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
		userService.addUser(user);
		
		// creates a simple e-mail object
		SimpleMailMessage email = new SimpleMailMessage();
		email.setTo(user.getEmail());
		email.setSubject("Welcome to Social Network");
		email.setText("Congratulations! You Have a Social Network Account");
		
		try{
			mailSender.send(email);
		}catch(Exception exception){
			exception.printStackTrace();
		}

		return "redirect:/SignUp";
	}
	
	//get log4j handler
	private static final Logger logger = Logger.getLogger(Registration.class);
	
}
